<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    /**
    * Main class for working with real estate objects
    * @author NU SIT Bar
    * @version 1.0                        
    * 17:39:44 h
    */

    class Objects extends MX_Controller 
    {

        private $data = array();

        function __construct()
        {

            parent::__construct();
            if(!$this->session->userdata('logged_in')){
                redirect(base_url());    
            }
            $this->load->config('pages');
            $this->load->config('gallery');

            $this->load->model('objects_model');
            $this->load->model('object_groups_model');
            $this->load->model('group_attributes_model');
            $this->load->model('groups_model');
            $this->load->model('objects_type_model');
            $this->load->model('destinations_model');   
            $this->load->helper('inflector');
            $this->load->helper('component');
            $this->load->library('translate', array('lang' => 'en'));
            $this->load->library('object_lib');

        }

        public function view_all()
        {
            $this->load->helper('fields');

            $this->data = array_merge($this->data, array(
                    'title' => 'Objects',
                    'page' => 'Realestate',
                    'objects' => fileds_result_array($this->objects_model->list_all(),'object_fields')
                ));

            //$this->firephp->log($this->data);

            $this->template->build('objects/view_all',$this->data);
        }

        public function view_new()
        {
            $this->data = array_merge($this->data, array(

                    'title' => 'New Object',
                    'page' => 'Realestate',
                    'post_action' => 'NEW',
                    'post_type' => $_GET['post_type'],
                    'object_types' => $this->objects_type_model->find_all(),
                    'destinations' => $this->destinations_model->get_all_parents()

                ));

            $this->template->build('objects/edit_general',$this->data);
        }

        public function view_edit($object_id)
        {
            // GET OBJECT
            $object = $this->objects_model->list_by_id($object_id);
            // GET GENERAL ID ON OBJECT
            $object_groups = $this->object_groups_model->find_general_group($object['object_type_ID']);
            // GET ATTRIBUTES ON GENERAL GROUP
            $general_attributes = $this->group_attributes_model->get_attributes_on_group($object_groups['group_ID']);
            // GET HTML ON GENERAL GROUP
            $general_html = $this->groups_model->get_html_on_group($general_attributes,$object['object_fields'],$object_groups['group_ID']);            

            $this->data = array_merge($this->data, array(

                    'object' => $object,
                    'general_group_ID' => $object_groups['group_ID'],
                    'general_html' => $general_html,
                    'title' => 'Edit Object',
                    'page' => 'Realestate',
                    'post_action' => 'EDIT',
                    'post_type' => $_GET['post_type'],
                    'object_types' => $this->objects_type_model->find_all(),
                    'destinations' => $this->destinations_model->get_all_parents()

                ));

            $this->template->build('objects/edit_general',$this->data);
        }

        public function general_html($object_type_ID)
        {
            // GET GENERAL ID ON OBJECT
            $object_groups = $this->object_groups_model->find_general_group($object_type_ID);
            // GET ATTRIBUTES ON GENERAL GROUP
            $general_attributes = $this->group_attributes_model->get_attributes_on_group($object_groups['group_ID']);
            // GET HTML ON GENERAL GROUP
            $general_html = $this->groups_model->get_html_on_group($general_attributes,NULL,$object_groups['group_ID']); 

            echo json_encode(array('action'=>TRUE,'general_html'=>$general_html,'general_group_id'=>$object_groups['group_ID']));
        }

        // Todo: Validate custom required attributes from DB
        public function submit_general_form()
        {

            $validation_info = 'object';
            if($_POST['post_action']=='NEW'):
                $this->form_validation->set_rules("object_type_ID", "type", "dropdown_check[$validation_info]");
                endif;

            // GET GENERAL ID ON OBJECT
            $object_groups = $this->object_groups_model->find_general_group($_POST['object_type_ID']);
            $general_group_ID = $object_groups['group_ID'];


            $this->form_validation->set_rules("object_destination", "destination", "dropdown_check[$validation_info]");

            // GET ALL ATTRIBUTES ON GROUP AND CREATE VALIDATION RULES
            $required = $this->group_attributes_model->get_attributes_on_group($general_group_ID,NULL,TRUE,TRUE);
            $this->load->library('translate');
            foreach ($required as $attribute):

            $attribute_name = $this->translate->find_lang_field($attribute['attribute_name'],'en');

            switch ($attribute['attribute_type']) {
                case 'descriptive data':
                    $this->form_validation->set_rules($general_group_ID."___".format_input_name($attribute_name).'[0]', strtolower($attribute_name), "required|xss_clean");
                    break;
                case 'yes/no':
                    $this->form_validation->set_rules($general_group_ID."___".format_input_name($attribute_name), strtolower($attribute_name), "required|xss_clean");
                    break;
                case 'numeric':
                    $this->form_validation->set_rules($general_group_ID."___".format_input_name($attribute_name), strtolower($attribute_name), "required|xss_clean|numeric");
                    break;
                case 'area':
                    $this->form_validation->set_rules($general_group_ID."___".format_input_name($attribute_name), strtolower($attribute_name), "required|xss_clean");
                    break;
                case 'distance':
                    $this->form_validation->set_rules($general_group_ID."___".format_input_name($attribute_name), strtolower($attribute_name), "required|xss_clean");
                    break;
            }

            endforeach;

            $this->form_validation->set_message("required","Please enter $validation_info <b>%s</b>!");
            if ($this->form_validation->run() == FALSE)
            {
                echo json_encode(array('action'=>FALSE, 'msg'=>validation_errors()));
                return;
            } 

            //parse language fields from input array[] in post
            $post = $this->object_lib->parse_post($_POST,config_item('wp_languages'));
            /*print_r($post);
            exit;*/
            $this->firephp->log($post);

            // DO SOME DATA ARRANGEMENT
            $object_type_ID = $post['object_type_ID'];
            $destinations_ID = $post['object_destination'];
            $post_action = $post['post_action'];
            unset($post['object_type_ID']);
            unset($post['object_destination']);
            unset($post['post_action']);

            // trim whitespace form price
            $post[$general_group_ID."___price"] = trim($post[$general_group_ID."___price"]);

            if($post_action=='EDIT'){

                // GET OBJECT
                $object = $this->objects_model->list_by_id($post['object_ID']);
                // GET GENERAL ID ON OBJECT
                $object_groups = $this->object_groups_model->find_general_group($object['object_type_ID']);
                // GET ATTRIBUTES ON GENERAL GROUP
                $fields = unserialize($object['object_fields']);
                //$this->firephp->log($fields);
                $general_attributes = $this->group_attributes_model->get_attributes_on_group($object_groups['group_ID']);
                //$this->firephp->log($general_attributes);
                // List all attributes in group
                foreach($general_attributes as $attribute) {  

                    $attribute_name = format_input_name($this->translate->find_field('en',$attribute['attribute_name']));
                    //$this->firephp->log($attribute_name);
                    if(isset($post[$object_groups['group_ID'].'___'.$attribute_name]))
                    {
                        //$this->firephp->log('is set');
                        $fields[$object_groups['group_ID'].'___'.$attribute_name] = $post[$object_groups['group_ID'].'___'.$attribute_name];
                    }else
                    {
                        unset($fields[$object_groups['group_ID'].'___'.$attribute_name]);
                    }

                } 
                //$this->firephp->log($fields);


                $object_ID = $post['object_ID'];
                unset($post['object_ID']);
            }else
            {
                $fields = $post;
            }    

            $data = array(
                'destinations_ID' => $destinations_ID,
                'status' => 1,
                'date_time' => time(),
                'fields' => serialize($fields),
            );

            switch ($post_action) {
                case "EDIT":
                    $this->objects_model->update($object_ID,$data);
                    $success = ($this->db->affected_rows()>=0);
                    if ($this->db->affected_rows()>=0)
                    {
                        echo json_encode(array("action"=>true,"msg"=>"Successful edit operation."));
                        return;
                    }
                    break;
                case "NEW":
                    $data['object_type_ID'] = $object_type_ID;
                    $object_id = $this->objects_model->insert($data);
                    if($object_id)
                    {
                        $this->load->helper('folder');
                        $this->load->config('gallery');
                        $this->load->library("gallery");
                        $this->load->library("object_gallery_lib");

                        // insert into gallery
                        $gallery_id = $this->gallery->add($object_id);
                        // insert into gallery_objects
                        $this->object_gallery_lib->add($object_id,$gallery_id);

                        // create gallery folder for new object
                        $this->gallery->create_main_direcoty($object_id);

                        // create thumbnails directories from gallery config
                        $this->gallery->create_thumbnails_directories($object_id);

                        echo json_encode(array("action"=>true,"msg"=>"Successful inser operation. Please navigate with links added on top of page to complete you object descriptions.","insert_id"=>$object_id));
                        return;
                    }
            }

            // If comes to thisd line, error ocured
            echo json_encode(array('action'=>FALSE, 'msg'=>'<p>This should not heppend :)</p>')); 

        }

        public function delete($object_ID)
        {   
            // find gallery id
            $this->load->library('object_gallery_lib');
            $gallery_id = $this->object_gallery_lib->find_gallery_column($object_ID,'gallery_ID');
            $folder = $this->object_gallery_lib->find_gallery_column($object_ID,'path');

            // delete gallery pictures and main gallery folder
            $this->load->library('gallery');
            $this->gallery->delete($gallery_id,$folder);

            // delete object an object_gallery
            $this->objects_model->delete($object_ID);

            // reload page to preview pictures
            redirect(base_url('objects/view_all?post_type=realestate'));
        }
    }

?>
